package com.zsg.webview.Activities;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.JsonObjectRequest;
import com.zsg.webview.Config;
import com.zsg.webview.R;
import com.zsg.webview.Util.Net;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity implements Config {

    public static final String TAG = "MainActivity";
    WebView webView;
    int bbbb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webView = (WebView) findViewById(R.id.webView);
        webView.setBackgroundColor(0);      //设置webview背景透明
        //加载网页
        //webView.loadUrl("file:///android_assets/abc.html");
        webView.loadUrl(getCodeurl);

        //开启JavaScript
        webView.getSettings().setJavaScriptEnabled(true);

        //设置webview客户端   让网页可以直接在webview中打开
        webView.setWebViewClient(new MyWebViewClient());



    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //用户按下返回键  return false 会退出程序
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (webView.canGoBack()) {
                webView.goBack();
                return true;
            } else
                return super.onKeyDown(keyCode, event);
        }
        return super.onKeyDown(keyCode, event);
    }


    class MyWebViewClient extends WebViewClient {


        /**
         * 在页面加载开始时调用,
         * 用户登录后 微博服务器返回access_token
         * 获得回调的参数 （访问令牌）
         *
         * @param view
         * @param url
         * @return
         */
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            Log.d(TAG, url);
            //解析Url  得到code 令牌
            if (url.split("[?]").length > 1) {
                //分割url得到参数部分
                String paramUrl = url.split("[?]")[1];
                if (paramUrl != null) {   //  得到每个参数部分
                    String[] params = paramUrl.split("[&]");
                    for (String s : params) {
                        String[] temp = s.split("[=]");
                        //判断参数的键
                        if (temp[0].equals("code")) {

                            //执行异步任务 得到access_token
                            //new LoadTesk().execute(temp[1]);
                            getAccessToken(temp[1]);

                        }
                    }
                }
            }

        }

        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { // Handle the error
            //Toast.makeText(getApplicationContext(), "网络连接失败 ,请连接网络。", Toast.LENGTH_SHORT).show();
            //没有网的情况下  直接跳转
            Intent intent = new Intent(MainActivity.this, ShowActivity.class);
            startActivity(intent);
            finish();
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return super.shouldOverrideUrlLoading(view, url);
        }
    }

    /**
     * //得到code后 访问地址 得到access_token
     *
     * @param code
     */
    public void getAccessToken(final String code) {
        //请求地址
        String tokenUrl = "https://api.weibo.com/oauth2/access_token?" +
                "client_id=" + AppKey +
                "&client_secret=" + AppSecret +
                "&grant_type=authorization_code" +
                "&redirect_uri=" + RedirectUrl +
                "&code=" + code;


        JsonObjectRequest request = new JsonObjectRequest(
                Request.Method.POST,
                tokenUrl,
                null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                          Log.d(TAG, " 令牌" + response.toString());
                        try {
                            String token = response.getString("access_token");
                            Intent intent = new Intent(MainActivity.this, ShowActivity.class);
                            //intent.putExtra("CODE", token);
                            //保存access_taken到选项存储
                            saveTaken(token);
                            startActivity(intent);
                            finish();

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                null

        );


        Net.getInstance(getApplicationContext())
                .addRequest(request);


    }


    /**
     * 得到code后 访问地址 得到access_token
     * 接受参数  进度  返回结果
     */
    class LoadTesk extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {

            String data = "error";

            //网络操作
            //请求地址
            String tokenUrl = "https://api.weibo.com/oauth2/access_token?" +
                    "client_id=" + AppKey +
                    "&client_secret=" + AppSecret +
                    "&grant_type=authorization_code" +
                    "&redirect_uri=" + RedirectUrl +
                    "&code=" + params[0];
            Log.d(TAG, tokenUrl);

            try {
                //url  统一资源定位符   uri统一资源id
                URL url = new URL(tokenUrl);
                //打开连接
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                connection.connect();

                //读取数据  包装成字符流
                InputStreamReader isr = new InputStreamReader(connection.getInputStream());
                char[] buf = new char[1024];
                int size;
                StringBuilder sb = new StringBuilder();
                while ((size = isr.read(buf)) != -1) {
                    sb.append(buf, 0, size);
                }

                isr.close();
                data = sb.toString();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return data;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            try {
                JSONObject json = new JSONObject(s);
                String token = json.getString("access_token");
                Intent intent = new Intent(MainActivity.this, ShowActivity.class);
                // intent.putExtra("CODE", token);
                //保存access_taken到选项存储
                saveTaken(token);
                startActivity(intent);
                finish();

            } catch (JSONException e) {
                e.printStackTrace();
            }


        }
    }

    /**
     * 保存taken到磁盘
     * @param taken
     */
    private void saveTaken(String taken) {
        SharedPreferences settings = getSharedPreferences(FILE_NAME, MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString(TAKEN, taken);
        editor.commit();
    }


}
